import {Component, ViewChild,ChangeDetectorRef } from '@angular/core';
import {Content, IonicPage, NavController,AlertController,NavParams, TextInput, ToastController,ViewController} from 'ionic-angular';
import {USERFACE_PATH} from "../../providers/Constants";
import {JmessageChenyu} from "jmessage-chenyu";
import {UserInfo} from "../../model/UserInfo";
import {StorageService} from "../../providers/StorageService";
import {BaseUI} from "../../common/baseui";
import {MessageModel} from "../../model/MessageModel";
import {UserService} from "../../providers/UserService";
@IonicPage()
@Component({
  selector: 'page-chatdetail',
  templateUrl: 'chatdetail.html',
})
export class ChatdetailPage extends BaseUI{

  chatUserNickName:string;
  chatUserFace:string;
  chatUserPhone:string;
  chatUserId:string;
  userFacePath:string;
  messageList:MessageModel[]=[];

  sendMessage:string=null;

  @ViewChild(Content) content: Content; //全局的 content
  @ViewChild('chatInput') messageInput: TextInput; //获取前台的输入框

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private jmessageChenyu:JmessageChenyu,
              public userInfo:UserInfo,
              public storageService:StorageService,
              public toastCtrl:ToastController,
              public viewCtrl:ViewController,
              private cdRef: ChangeDetectorRef,
              private userService:UserService,
              private  alertCtrl:AlertController) {

    super();
    this.chatUserNickName = this.navParams.get('chatUserNickName');
    this.chatUserFace = this.navParams.get('chatUserFace');
    this.chatUserPhone = this.navParams.get('chatUserPhone');
    this.chatUserId = this.navParams.get('chatUserId');
    this.userFacePath = USERFACE_PATH;

    this.userInfo=this.storageService.read<UserInfo>('UserInfo');
  }

  ionViewDidLoad() {
    this.createConversation();//创建会话

  }


  //接受消息类
  NewAddReceiveMessageListener(){
    this.jmessageChenyu.addReceiveMessageListener((msg)=>{//接收消息

      if(msg.from.username==this.chatUserPhone){//判断消息的来源是否为当前聊天对象
        this.messageList.push(msg);
        this.cdRef.detectChanges();
        this.scrollToBottom();
        this.focus();
      }
    });
  }

  SendMessage(){
    if(this.sendMessage==undefined || this.sendMessage==null){
      super.showToast(this.toastCtrl,'发送内容不能为空','bottom');
      return;
    }

      this.jmessageChenyu.sendTextMessage({ type: 'single', username: this.chatUserPhone,
          text: this.sendMessage}).then((msg)=>{
          let result = localStorage.getItem(this.chatUserId);
          if(!result){   //未进行过会话(第一次会话提示用户是否添加联系人)
            this.addContactPerson(this.userInfo.id,this.chatUserId);
            localStorage.setItem(this.chatUserId,this.chatUserId);
          }
          this.messageList.push(msg);
          this.cdRef.detectChanges();
           this.scrollToBottom();
            this.sendMessage=null;
          }).catch(error=>{
            alert("发送失败"+JSON.stringify(error));
      })
  }

  focus() {
    this.content.resize();
    this.scrollToBottom();
  }

  scrollToBottom(): any {
    setTimeout(() => {
      if (this.content.scrollToBottom) {
        this.content.scrollToBottom();
      }
    }, 400);
  }
  //获取历史会话消息
  getHistoryMessages(){
      this.jmessageChenyu.getHistoryMessages({ type: 'single', username:this.chatUserPhone,
        from: 0, limit: -1 }).then((msgList)=>{
        // alert(JSON.stringify(msgList));
        if(msgList!=undefined ||msgList!=null){
          for(var i= 0;i<msgList.length;i++){
            this.messageList.push(msgList[i]);
          }
        }

      }).catch((error)=>{
        super.showToast(this.toastCtrl,JSON.stringify(error),'middle');
      })
  }
  //创建会话
  createConversation(){
    this.jmessageChenyu.createConversation({type:'single',username: this.chatUserPhone}).then((conversation)=>{
      this.NewAddReceiveMessageListener();//进行消息监听
      this.getHistoryMessages();//获取历史消息
    }).catch(error=>{
      super.showToast(this.toastCtrl,'发起聊天失败','middle');
      this.viewCtrl.dismiss();
    })
  }

   formatDate(time) {
     // return new Date(parseInt(date)*1000).toLocaleString().replace(/:d{1,2}$/,'')
     //return new Date(parseInt(date)*1000).toLocaleString().replace(/年|月/g,"-").replace(/日/g,' ')
     var now=new Date(time);
     var year=now.getFullYear();
     var month=now.getMonth()+1;
     var date=now.getDate();
     var hour=now.getHours();
     var minute=now.getMinutes();
     var second=now.getSeconds();
     return year+"年"+month+"月"+date+"日  "+hour+":"+minute+":"+second;
   }

   addContactPerson(userId,toUserId){
     let confirm = this.alertCtrl.create({
       message: '是否添加到联系人？(长按对方头像也可添加联系人)',
       buttons: [
         {
           text: '否',
           handler: () => {
           }
         },
         {
           text: '是',
           handler: () => {
             this.userService.addContactPerson(userId,toUserId).subscribe(res=>{
               super.showToast(this.toastCtrl,res['msg'],'bottom');
             })
           }
         }
       ]
     });
     confirm.present();
   }


}
